package com.hut.oa.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.hut.oa.model.bean.Attachment;
import com.hut.oa.model.dao.AttachmentDao;
import com.hut.oa.model.dao.user.UserDao;

/**
 * 附件
 * @author 朱嘉茵
 *
 */
@Service
public class AttachmentService {
	Logger log=LoggerFactory.getLogger(getClass());
	
	@Value(value ="${file.upload.path}")
	private String rootPath;//根目录
	
	@Autowired
	AttachmentDao ad;
	
	@Autowired
	UserDao ud;
	
	/**
	 * 附件上传
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	public Attachment saveAttachment(MultipartFile file, Long userId, String module) throws IllegalStateException, IOException{
		
		//拼接存储路径
		StringBuffer pathName=new StringBuffer(module);//模块
		/*pathName.append("/");
		pathName.append(ud.findById(userId).getName());*///用户
		pathName.append("/");
		pathName.append(new SimpleDateFormat("yyyy/MM").format(new Date()));//日期
		
		File savePath=new File(rootPath,pathName.toString());
		log.info("附件存储路径： {}",savePath.getAbsolutePath());
		
		//建立文件夹
		if(!savePath.exists()){
			savePath.mkdirs();
		}
		
		//修改文件名
		String suffix=FilenameUtils.getExtension(file.getOriginalFilename());//后缀
		String fileName=UUID.randomUUID().toString().toLowerCase() + "." + suffix;//文件名
		//上传文件
		File uploadFile=new File(savePath,fileName);
		String filePath=uploadFile.getAbsolutePath().replace(rootPath, "");
		file.transferTo(uploadFile);
		
		//保存到数据库
		Attachment a=new Attachment(file.getContentType(),file.getOriginalFilename(),filePath , file.getSize(), userId, module, suffix);	
		return ad.save(a);
	}
	
	/**
	 * 获取附件
	 * @param a
	 * @return
	 */
	public File getFilePath(Attachment a){
		File file=new File(rootPath,a.getPath());
		return file;
	}
	/**
	 * 附件下载
	 */
	public void dowloadAtt(Attachment att,HttpServletResponse response){
		File file=this.getFilePath(att);
		try {
			// 设置下载的请求头信息
			// 显示文件大小
			response.setContentLength(att.getSize().intValue());
			// 下载时显示文件类型
			response.setContentType(att.getType());
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(att.getName().getBytes("UTF-8"), "ISO8859-1"));
			ServletOutputStream sos = response.getOutputStream();
			// 读取文件问字节码
			byte[] data = new byte[att.getSize().intValue()];
			FileInputStream input = new FileInputStream(file);
			IOUtils.readFully(input, data);
			// 将文件流输出到浏览器
			IOUtils.write(data, sos);
			input.close();
			sos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
